#!/bin/bash

# 1. 进入脚本所在目录
script_dir="$(cd $(dirname .); pwd)"
cd "${script_dir}"

# 2. 参数校验
if [[ "${1}" == "" ]]; then
    echo "Usage: ${0} <module_name>"
    exit 1
fi

# 3. 检测文件是否存在
if [ -d "$1" ]; then
    echo "directory \"$1\" exists"
    exit 1
fi

if [ -f "$1" ]; then
    echo "File \"$1\" exists"
    exit 1
fi

# 4. 创建模块目录
mkdir -p "$1"
filename=$(basename "$1")
echo "Generating module \"$filename\""

# 5. 生成模块源文件
funcname=$(echo "${filename}" | tr '-' '_')
touch "$1/$filename.c"
cat << EOF > "$1/$filename.c"
#include <linux/init.h>
#include <linux/module.h>

static int __init ${funcname}_init(void)
{
    printk("[%s]: Hello, world!\n", __func__);
    return 0;
}

static void __exit ${funcname}_exit(void)
{
    printk("[%s]: Goodbye, world!\n", __func__);
}

module_init(${funcname}_init);
module_exit(${funcname}_exit);

MODULE_LICENSE("GPL");
EOF

# 5. 生成模块 Makefile
touch "$1/Makefile"
cat << EOF > "$1/Makefile"
obj-m := ${filename}.o
EOF